package cn.topcodes.tcsf.wechat.listener;

import cn.topcode.unicorn.wxsdk.WXMessageListener;
import cn.topcode.unicorn.wxsdk.message.receive.event.SubscribeEvent;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMp;
import cn.topcodes.tcsf.wechat.domain.entity.WechatUser;
import cn.topcodes.tcsf.wechat.domain.entity.WechatUserBranch;
import cn.topcodes.tcsf.wechat.service.WechatMpService;
import cn.topcodes.tcsf.wechat.service.WechatUserBranchService;
import cn.topcodes.tcsf.wechat.service.WechatUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by Unicorn on 2017/8/15.
 */
@Component
@Lazy(false)
public class SubscribeListener extends WXMessageListener<SubscribeEvent> {

    @Autowired
    private WechatUserServiceImpl wechatUserService;

    @Autowired
    private WechatMpService wechatMpService;

    @Autowired
    private WechatUserBranchService wechatUserBranchService;

    @Override
    public void onReceive(SubscribeEvent src) {
        String openId = src.getFromUserName();
        WechatUser wechatUser = this.wechatUserService.findByOpenId(openId);
        //  若用户第一次关注将从微信服务器获取用户信息并入库，再次关注则更新状态
        if(SubscribeEvent.EVENT_SUBSCRIBE.equals(src.getEvent())) {
            if(wechatUser == null) {
                this.wechatUserService.saveWechatUserFromMp(src.getToUserName(), openId);
            }else {
                wechatUser.setSubscribe(WechatUser.SUBSCRIBE_TRUE);
                this.wechatUserService.update(wechatUser);
                WechatMp wechatMp = wechatMpService.findWechatMpByMpId(src.getToUserName());
                if(wechatMp != null) {
                    WechatUserBranch branch = wechatUserBranchService.findBy(wechatMp.getId(), src.getFromUserName());
                    if(branch != null) {
                        branch.setSubscribe(WechatUser.SUBSCRIBE_TRUE);
                        branch.setSubscribeTime(new Date());
                        wechatUserBranchService.save(branch);
                    }
                }
            }
        }else if(SubscribeEvent.EVENT_UNSUBSCRIBE.equals(src.getEvent())) {
            if(wechatUser != null) {
                wechatUser.setSubscribe(WechatUser.SUBSCRIBE_FALSE);
                this.wechatUserService.update(wechatUser);
                WechatMp wechatMp = wechatMpService.findWechatMpByMpId(src.getToUserName());
                if(wechatMp != null) {
                    WechatUserBranch branch = wechatUserBranchService.findBy(wechatMp.getId(), src.getFromUserName());
                    if(branch != null) {
                        branch.setSubscribe(WechatUser.SUBSCRIBE_FALSE);
                        branch.setSubscribeTime(new Date());
                        wechatUserBranchService.save(branch);
                    }
                }
            }
        }
    }
}
